<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>文件上传下载</title>
    <script>
        function loadFileList() {
            fetch('${pageContext.request.contextPath}/getFilesName')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.text();
                })
                .then(data => {
                    try {
                        const files = JSON.parse(data);
                        let html = '<h3>可下载文件列表:</h3><ul>';
                        if (files.length === 0) {
                            html += '<li>暂无文件</li>';
                        } else {
                            files.forEach(function(file) {
                                html += '<li><a href="${pageContext.request.contextPath}/download?filename='
                                      + encodeURIComponent(file.name) + '">' + file.name + '</a></li>';
                            });
                        }
                        html += '</ul>';
                        document.getElementById('fileList').innerHTML = html;
                    } catch (e) {
                        console.error('Error parsing JSON:', e);
                        document.getElementById('fileList').innerHTML = '<p>加载文件列表失败</p>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('fileList').innerHTML = '<p>加载文件列表失败</p>';
                });
        }

        window.onload = function() {
            loadFileList();

            // 检查URL参数显示提示信息
            const urlParams = new URLSearchParams(window.location.search);
            const success = urlParams.get('success');
            const messageDiv = document.getElementById('message');

            if (success === 'true') {
                messageDiv.innerHTML = '<div style="color: green; margin: 10px 0;">文件上传成功！</div>';
            } else if (success === 'false') {
                messageDiv.innerHTML = '<div style="color: red; margin: 10px 0;">文件上传失败，请重试！</div>';
            }
        };
    </script>
</head>
<body>
    <h2>文件上传</h2>
    <div id="message"></div>

    <form action="${pageContext.request.contextPath}/fileUpload"
          method="post" enctype="multipart/form-data">
        选择文件: <input type="file" name="file" required><br/><br/>
        <input type="reset" value="清空"/>
        <input type="submit" value="上传文件"/>
    </form>

    <div id="fileList"></div>

    <br/>
    <a href="${pageContext.request.contextPath}/">返回首页</a>
</body>
</html>